﻿using System;
using System.Collections.Generic;
using System.Text;
using B4ALL.Common;

namespace B4ALL.Cache
{
    public class CacheService : ICacheService
    {

        private IDataCacheManager cacheManager;

        public IDataCacheManager CacheManager
        {
            get { return cacheManager; }
            set { cacheManager = value; }
        }
        

        List<ICacheHandler> handlers = null;

        public List<ICacheHandler> Handlers
        {
            get {
                if (handlers == null)
                    handlers = new List<ICacheHandler>();

                return handlers;
            }
            set { handlers = value; }
        }
        

        #region ICacheService Members

        public void OnEntry(PostSharp.Laos.MethodExecutionEventArgs eventArgs, PostSharp.Laos.OnMethodBoundaryAspect aspect)
        {
            CacheContext cacheContext = Context.GetContext<CacheContext>();

            if (cacheManager != null && (cacheContext == null || cacheContext.Enabled) && (cacheContext == null || (cacheContext.Refresh.HasValue && cacheContext.Refresh.Value)))
            {
                foreach (ICacheHandler cacheHandler in handlers)
                {
                    HandlerBehavior hb = cacheHandler.OnEntry(eventArgs, aspect);
                    if (eventArgs.FlowBehavior == PostSharp.Laos.FlowBehavior.Return || hb == HandlerBehavior.Break)
                        break;
                }
            }
        }

        public void OnSuccess(PostSharp.Laos.MethodExecutionEventArgs eventArgs, PostSharp.Laos.OnMethodBoundaryAspect aspect)
        {
            CacheContext cacheContext = Context.GetContext<CacheContext>();

            if (cacheManager != null && (cacheContext == null || cacheContext.Enabled))
            {
                foreach (ICacheHandler cacheHandler in handlers)
                {
                    HandlerBehavior handleBehavior = cacheHandler.OnSuccess(eventArgs, aspect);
                    if (handleBehavior == HandlerBehavior.Break)
                        break;
                }
            }
        }

        #endregion
    
    }
}